<?php

namespace App\Http\Controllers\Admin;

use App\Models\Attachment;
use FoxLib\Exceptions\FileUploadException;
use FoxLib\Services\OssService;

class AttachmentController extends Controller
{

    /*
     * @api get /course-api/a/attachments 附件列表
     * @version 0.0.1
     * @group admin
     *
     * @param query int [pageSize] 页数，默认15
     * @param query int [page] 页码，默认1
     * @param query int [type] 附件类型，0图片（默认），1音频，2视频
     * @param query string [name] 附件名称
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":10,
     *    "items":[]
     * }
     * }
     */
    public function index()
    {
        $this->validate($this->request, [
            'pageSize' => "integer|max:100|min:5",
            'page' => "integer|min:1",
            'type' => 'integer',
            'name' => 'string'
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        $name = $this->request->input('name');
        $type = $this->request->input('type', null);

        $query = Attachment::query();
        if (!is_null($type)) {
            $query->ofType($type);
        }
        if ($name) {
            $query->where('name', 'like', "%{$name}%");
        }
        $total = $query->count();
        $attachments = $query->orderBy('id', 'desc')->forPage($page, $pageSize)
            ->get();
        $items = [];
        if ($total) {
            /** @var Attachment $attachment */
            foreach ($attachments as $attachment) {
                $uri = $attachment->getUri();
                if ($attachment->getType() === 0) {
                    // $uri = $uri . '?x-oss-process=style/word';
                }
                $items[] = [
                    'id' => $attachment->id,
                    'name' => $attachment->getName(),
                    'uri' => $uri,
                    'ext' => $attachment->getExt(),
                    'properties' => $attachment->getProperties()
                ];
            }
        }
        return $this->sendSuccessJson(['total'=>$total, 'items'=>$items]);
    }

    /*
     * @api post /course-api/a/attachments 上传附件
     * @version 0.0.1
     * @group admin
     *
     * @param body file file 上传的资源
     * @param body int [type] 附件类型，0图片（默认），1音频，2视频
     * @param body int [isRecognize] 是否需要语音识别，0不需要（默认），1需要
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *    "total":10,
     *    "items":[]
     * }
     * }
     */
    public function store()
    {
        if (!$this->request->hasFile('file')) {
            throw new FileUploadException();
        }
        $uploadFile = $this->request->file('file');
        $size = $uploadFile->getSize();
        $originalName = $uploadFile->getClientOriginalName();
        $filePath = $uploadFile->getPathname();
        $pathInfo = pathinfo($originalName);
        $type = $this->request->input('type', Attachment::TYPE['image']);
        $properties = [];
        if ($type == Attachment::TYPE['image']) {
            list($width, $height) = getimagesize($filePath);
            $properties = [
                'width' => $width,
                'height' => $height
            ];
        }
        $uri = OssService::upload($filePath, $pathInfo['extension']);
        $attachmentObj = new Attachment();
        $attachmentObj->setName($pathInfo['filename']);
        $attachmentObj->setExt($pathInfo['extension']);
        $attachmentObj->setSize($size);
        $attachmentObj->setType($type);
        $attachmentObj->setUri($uri);
        $attachmentObj->setProperties($properties);
        $attachmentObj->save();
        $data = [
            'id' => $attachmentObj->id,
            'name' => $pathInfo['filename'],
            'uri' => $uri,
            'ext' => $pathInfo['extension'],
            'properties' => $properties
        ];
        return $this->sendSuccessJson($data);
    }

    /*
     * @api put /course-api/a/attachments/{attachmentId} 更新附件
     * @version 0.0.1
     * @group admin
     *
     * @param body string name 名称
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function update($id)
    {
        $this->request->merge(['id' => $id]);
        $this->validate($this->request, [
            'id' => 'required|integer',
            'name' => 'required|string',
        ]);
        $name = $this->request->input('name');

        /** @var Attachment $attachmentObj */
        $attachmentObj = Attachment::find($id);
        $attachmentObj->setName($name);
        $attachmentObj->save();
        return $this->sendSuccessJson();
    }

    /*
     * @api delete /course-api/a/attachments/{attachmentId} 删除附件
     * @version 0.0.1
     * @group admin
     *
     * @param path int attachmentId 附件ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function destroy($id)
    {
        Attachment::destroy(intval($id));
        return $this->sendSuccessJson();
    }
}
